package com.example.taobaolianmeng.presenter.impl;

import android.annotation.SuppressLint;
import android.util.Log;

import com.example.taobaolianmeng.model.Api;
import com.example.taobaolianmeng.model.domain.HomePagerContent;
import com.example.taobaolianmeng.presenter.ICategoryPagerPresenter;
import com.example.taobaolianmeng.utils.RetrofitManager;
import com.example.taobaolianmeng.utils.UrlUtils;
import com.example.taobaolianmeng.view.ICategoryPagerCallback;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class CategoryPagePresenterImpl implements ICategoryPagerPresenter {

    private static final String TAG = "CategoryPagePresenterImpl";
    private Map<Integer,Integer> pagesInfo = new HashMap<>();

    public static final int DEFAULT_PAGE = 1;
    private Integer mCurrentPage;



    @SuppressLint("LongLogTag")
    @Override
    public void getContentByCategoryId(int categoryId) {
        //加载loading状态
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                callback.onLoading();
            }
        }
        //根据分类id去加载内容
        Integer targetPage = pagesInfo.get(categoryId);
        if(targetPage == null) {
            targetPage = DEFAULT_PAGE;
            pagesInfo.put(categoryId,targetPage);
        }
        Call<HomePagerContent> task = createTask(categoryId, targetPage);
        task.enqueue(new Callback<HomePagerContent>() {
            @Override
            public void onResponse(Call<HomePagerContent> call, Response<HomePagerContent> response) {
                int code = response.code();
                Log.d(TAG,"code is "+ code);
                if(code == HttpURLConnection.HTTP_OK){
                    HomePagerContent pagerContent = response.body();
//                    Log.d(TAG,"pagerContent ->"+pagerContent);
                    //把数据给到ui
                    handleHomePageContentResult(pagerContent,categoryId);
                }else{
                    //TODO
                    handleNetworkError(categoryId);
                }

            }

            @Override
            public void onFailure(Call<HomePagerContent> call, Throwable t) {
                Log.d(TAG,"onFailure..."+t.toString());
                handleNetworkError(categoryId);
            }
        });

    }

    //创建api请求任务
    @SuppressLint("LongLogTag")
    private Call<HomePagerContent> createTask(int categoryId, Integer targetPage) {
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        Api api = retrofit.create(Api.class);
        String homePagerUrl = UrlUtils.createHomePagerUrl(categoryId, targetPage);
        Log.d(TAG,"homePagerUrl->"+homePagerUrl);
        return api.getHomePageContent(homePagerUrl);
    }

    private void handleNetworkError(int categoryId) {
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                callback.onNetworkError();
            }
        }
    }

    private void handleHomePageContentResult(HomePagerContent pageContent, int categoryId) {
        //通知ui跟新数据
        List<HomePagerContent.DataBean> data = pageContent.getData();
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                if (pageContent == null || pageContent.getData().size() == 0) {
                    callback.onEmpty();
                } else {
                    List<HomePagerContent.DataBean> looperData = data.subList(data.size() - 5, data.size());
                    callback.onLooperListLoaded(looperData);
                    callback.onContentLoaded(data);
                }
            }
        }
    }

    @Override
    public void loaderMore(int categoryId) {
        //加载更多数据
        //1.拿到当前页码
        mCurrentPage = pagesInfo.get(categoryId);
        if(pagesInfo ==null){
            mCurrentPage =1;
        }
        //2.页码++
        mCurrentPage++;
        //3.加载数据
        Call<HomePagerContent> task = createTask(categoryId, mCurrentPage);
        //4.处理数据结果
        task.enqueue(new Callback<HomePagerContent>() {
            @SuppressLint("LongLogTag")
            @Override
            public void onResponse(Call<HomePagerContent> call, Response<HomePagerContent> response) {
                //结果
                int code = response.code();
                Log.d(TAG,"code->"+code);
                if(code==HttpURLConnection.HTTP_OK){
                    HomePagerContent result = response.body();
                    Log.d(TAG,"result->"+result.toString());
                    handleLoaderResult(result,categoryId);
                }else{
                    handleLoadMoreError(categoryId);
                }
            }

            @SuppressLint("LongLogTag")
            @Override
            public void onFailure(Call<HomePagerContent> call, Throwable t) {
                Log.d(TAG,"onFailure...");
                handleLoadMoreError(categoryId);
            }
        });

    }

    private void handleLoaderResult(HomePagerContent result, int categoryId) {
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                if (result ==null || result.getData().size() ==0) {
                    callback.onLoadMoreEmpty();
                }else{
                    callback.onLoaderMoreLoaded(result.getData());
                }
            }
        }
    }

    private void handleLoadMoreError(int categoryId) {
        mCurrentPage--;
        pagesInfo.put(categoryId,mCurrentPage);
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                callback.onLoadMoreError();
            }
        }
    }

    @Override
    public void reload(int categoryId) {

    }

    private List<ICategoryPagerCallback> callbacks = new ArrayList<>();

    @Override
    public void registerViewCallback(ICategoryPagerCallback callBack) {
        if (!callbacks.contains(callBack)) {
            callbacks.add(callBack);
        }
    }

    @Override
    public void unregisterViewCallback(ICategoryPagerCallback callBack) {
        callbacks.remove(callBack);
    }
}
